<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <el-card class="box-card">
      <div class="survey-header">
        <div class="survey-title">
          <span v-if="surveyInfo.title">{{ surveyInfo.title }}</span>
          <span v-else class="placeholder">请输入问卷标题</span>
        </div>
        <div class="survey-actions">
          <el-button type="primary" icon="el-icon-check" @click="saveSurvey" :loading="saveLoading">保存</el-button>
          <el-button icon="el-icon-view" @click="previewSurvey">预览</el-button>
          <el-button icon="el-icon-back" @click="goBack">返回</el-button>
        </div>
      </div>
    </el-card>

    <!-- 内容主体 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 左侧问卷设计区 -->
      <el-col :span="18">
        <el-card class="box-card" v-loading="loading">
          <!-- 问卷基本信息 -->
          <div class="survey-basic-info">
            <div class="form-item">
              <div class="form-label required">问卷标题</div>
              <el-input v-model="surveyInfo.title" placeholder="请输入问卷标题" />
            </div>
            <div class="form-item">
              <div class="form-label">问卷描述</div>
              <el-input type="textarea" v-model="surveyInfo.description" placeholder="请输入问卷描述" :rows="3" />
            </div>
            <div class="form-row">
              <div class="form-item" style="flex: 1; margin-right: 20px;">
                <div class="form-label required">开始时间</div>
                <el-date-picker
                  v-model="surveyInfo.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  style="width: 100%;"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </div>
              <div class="form-item" style="flex: 1;">
                <div class="form-label required">结束时间</div>
                <el-date-picker
                  v-model="surveyInfo.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  style="width: 100%;"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </div>
            </div>
            <div class="form-row">
              <div class="form-item" style="flex: 1; margin-right: 20px;">
                <div class="form-label">匿名设置</div>
                <el-radio-group v-model="surveyInfo.anonymous">
                  <el-radio :label="1">匿名</el-radio>
                  <el-radio :label="0">不匿名</el-radio>
                </el-radio-group>
              </div>
              <div class="form-item" style="flex: 1;">
                <div class="form-label">显示结果</div>
                <el-radio-group v-model="surveyInfo.showResult">
                  <el-radio :label="1">显示</el-radio>
                  <el-radio :label="0">不显示</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div class="form-item">
              <div class="form-label">提交提示</div>
              <el-input v-model="surveyInfo.submitTip" placeholder="提交成功后显示的提示语" />
            </div>
          </div>

          <el-divider content-position="left">问题设计</el-divider>

          <!-- 问题列表 -->
          <div class="survey-questions">
            <draggable v-model="surveyInfo.questions" ghost-class="ghost" handle=".drag-handle" @end="updateQuestionSort">
              <div class="question-item" v-for="(question, index) in surveyInfo.questions" :key="'q' + question.tempId">
                <div class="question-card">
                  <div class="question-header">
                    <div class="drag-handle">
                      <i class="el-icon-rank"></i>
                    </div>
                    <div class="question-index">Q{{ index + 1 }}</div>
                    <div class="question-type-tag">{{ questionTypeMap[question.type] }}</div>
                    <div class="question-actions">
                      <el-tooltip content="上移" placement="top" :disabled="index === 0">
                        <el-button 
                          type="text" 
                          icon="el-icon-top" 
                          :disabled="index === 0"
                          @click="moveQuestion(index, 'up')" 
                        ></el-button>
                      </el-tooltip>
                      <el-tooltip content="下移" placement="top" :disabled="index === surveyInfo.questions.length - 1">
                        <el-button 
                          type="text" 
                          icon="el-icon-bottom" 
                          :disabled="index === surveyInfo.questions.length - 1"
                          @click="moveQuestion(index, 'down')" 
                        ></el-button>
                      </el-tooltip>
                      <el-tooltip content="复制" placement="top">
                        <el-button type="text" icon="el-icon-copy-document" @click="copyQuestion(index)"></el-button>
                      </el-tooltip>
                      <el-tooltip content="删除" placement="top">
                        <el-button type="text" icon="el-icon-delete" @click="deleteQuestion(index)"></el-button>
                      </el-tooltip>
                    </div>
                  </div>

                  <div class="question-content">
                    <div class="form-item">
                      <div class="form-label required">问题标题</div>
                      <el-input v-model="question.title" placeholder="请输入问题标题" />
                    </div>

                    <!-- 选择题选项 -->
                    <div class="form-item" v-if="question.type === 'radio' || question.type === 'checkbox'">
                      <div class="form-label required">选项设置</div>
                      <div 
                        class="option-item" 
                        v-for="(option, optIndex) in parseOptions(question.options)" 
                        :key="'opt' + optIndex"
                      >
                        <el-input 
                          v-model="option.label" 
                          placeholder="请输入选项文本"
                          @input="updateQuestionOptions(question, parseOptions(question.options))" 
                        />
                        <el-button 
                          type="text" 
                          icon="el-icon-delete" 
                          @click="deleteOption(question, optIndex)"
                        ></el-button>
                      </div>
                      <div class="add-option">
                        <el-button type="text" icon="el-icon-plus" @click="addOption(question)">添加选项</el-button>
                      </div>
                    </div>

                    <!-- 评分题设置 -->
                    <div class="form-item" v-if="question.type === 'rate'">
                      <div class="form-label">最高分</div>
                      <el-input-number v-model="question.maxScore" :min="3" :max="10" />
                    </div>

                    <!-- 填空题设置 -->
                    <div class="form-item" v-if="question.type === 'text'">
                      <div class="form-label">输入框行数</div>
                      <el-input-number v-model="question.rows" :min="1" :max="10" />
                    </div>
                    <div class="form-item" v-if="question.type === 'text'">
                      <div class="form-label">占位提示</div>
                      <el-input v-model="question.placeholder" placeholder="请输入占位提示" />
                    </div>

                    <div class="form-item">
                      <div class="form-label">是否必填</div>
                      <el-switch v-model="question.required" :active-value="1" :inactive-value="0" />
                    </div>
                  </div>
                </div>
              </div>
            </draggable>

            <!-- 添加问题按钮 -->
            <div class="add-question-container">
              <el-button type="dashed" class="add-question-btn" @click="showAddQuestionDialog">
                <i class="el-icon-plus"></i> 添加问题
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧控制面板 -->
      <el-col :span="6">
        <el-card class="box-card survey-setting">
          <div slot="header" class="clearfix">
            <span>问卷设置</span>
          </div>
          <div class="setting-content">
            <div class="setting-item">
              <div class="setting-label">问卷状态</div>
              <div class="setting-value">
                <el-tag :type="statusTypeMap[surveyInfo.status]">{{ surveyInfo.status | statusFilter }}</el-tag>
              </div>
            </div>
            <div class="setting-item" v-if="surveyId">
              <div class="setting-label">创建时间</div>
              <div class="setting-value">{{ parseTime(surveyInfo.createTime) }}</div>
            </div>
            <div class="setting-item" v-if="surveyId">
              <div class="setting-label">更新时间</div>
              <div class="setting-value">{{ parseTime(surveyInfo.updateTime) }}</div>
            </div>
            <div class="setting-item">
              <div class="setting-label">问题数量</div>
              <div class="setting-value">{{ surveyInfo.questions ? surveyInfo.questions.length : 0 }}个</div>
            </div>
            <div class="setting-item">
              <div class="setting-label">其他设置</div>
              <div class="setting-value">
                <el-button type="text" @click="showTargetSettingDialog">设置目标对象</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加问题对话框 -->
    <el-dialog title="添加问题" :visible.sync="addQuestionDialogVisible" width="500px" append-to-body>
      <div class="question-type-grid">
        <div
          class="question-type-item"
          v-for="type in questionTypes"
          :key="type.value"
          @click="addQuestion(type.value)"
        >
          <div class="question-type-icon">
            <i :class="type.icon"></i>
          </div>
          <div class="question-type-name">{{ type.label }}</div>
        </div>
      </div>
    </el-dialog>

    <!-- 目标设置对话框 -->
    <el-dialog title="设置目标对象" :visible.sync="targetSettingDialogVisible" width="600px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="目标部门">
          <el-select
            v-model="surveyInfo.targetDeptIds"
            multiple
            filterable
            placeholder="请选择目标部门"
            style="width: 100%;"
          >
            <el-option
              v-for="item in deptOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标角色">
          <el-select
            v-model="surveyInfo.targetRoleIds"
            multiple
            filterable
            placeholder="请选择目标角色"
            style="width: 100%;"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标用户">
          <el-select
            v-model="surveyInfo.targetUserIds"
            multiple
            filterable
            placeholder="请选择目标用户"
            style="width: 100%;"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="targetSettingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveTargetSetting">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 问卷预览对话框 -->
    <el-dialog title="问卷预览" :visible.sync="previewDialogVisible" width="800px" append-to-body>
      <div class="preview-container">
        <h2 class="preview-title">{{ surveyInfo.title }}</h2>
        <div class="preview-description">{{ surveyInfo.description }}</div>
        <div class="preview-info">
          <div>开始时间：{{ parseTime(surveyInfo.startTime) }}</div>
          <div>结束时间：{{ parseTime(surveyInfo.endTime) }}</div>
        </div>
        <div class="question-list">
          <div v-if="!surveyInfo.questions || surveyInfo.questions.length === 0" class="empty-questions">
            暂无问题，请先添加问题
          </div>
          <div v-else>
            <div class="question-item" v-for="(question, index) in surveyInfo.questions" :key="index">
              <div class="question-title">
                {{ index + 1 }}. {{ question.title }}
                <span class="required" v-if="question.required == 1">*</span>
              </div>
              <div class="question-content" v-if="question.type === 'radio'">
                <el-radio-group disabled>
                  <div v-for="(option, optIndex) in parseOptions(question.options)" :key="optIndex">
                    <el-radio :label="optIndex">{{ option.label }}</el-radio>
                  </div>
                </el-radio-group>
              </div>
              <div class="question-content" v-else-if="question.type === 'checkbox'">
                <el-checkbox-group disabled>
                  <div v-for="(option, optIndex) in parseOptions(question.options)" :key="optIndex">
                    <el-checkbox :label="optIndex">{{ option.label }}</el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
              <div class="question-content" v-else-if="question.type === 'text'">
                <el-input 
                  type="textarea" 
                  disabled 
                  :placeholder="question.placeholder || '请输入'" 
                  :rows="question.rows || 3" 
                />
              </div>
              <div class="question-content" v-else-if="question.type === 'rate'">
                <el-rate disabled :max="question.maxScore || 5" />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSurveyQuestionnaire, addSurveyQuestionnaire, updateSurveyQuestionnaire } from "@/api/system/survey";
import draggable from 'vuedraggable';

export default {
  name: "SurveyEdit",
  components: {
    draggable
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': '草稿',
        '1': '待审核',
        '2': '已发布',
        '3': '已结束',
        '4': '已归档'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      loading: false,
      saveLoading: false,
      surveyId: undefined,
      // 问卷基本信息
      surveyInfo: {
        title: '',
        description: '',
        startTime: '',
        endTime: '',
        status: '0',
        anonymous: 0,
        showResult: 0,
        submitTip: '感谢您的参与！',
        questions: []
      },
      // 问题类型
      questionTypes: [
        { label: '单选题', value: 'radio', icon: 'el-icon-circle-check' },
        { label: '多选题', value: 'checkbox', icon: 'el-icon-check' },
        { label: '填空题', value: 'text', icon: 'el-icon-edit-outline' },
        { label: '评分题', value: 'rate', icon: 'el-icon-star-on' }
      ],
      questionTypeMap: {
        'radio': '单选题',
        'checkbox': '多选题',
        'text': '填空题',
        'rate': '评分题'
      },
      statusTypeMap: {
        '0': '',      // 草稿
        '1': 'info',  // 待审核
        '2': 'success', // 已发布
        '3': 'warning', // 已结束
        '4': 'danger'  // 已归档
      },
      // 对话框显示控制
      addQuestionDialogVisible: false,
      targetSettingDialogVisible: false,
      previewDialogVisible: false,
      // 目标设置选项
      deptOptions: [],
      roleOptions: [],
      userOptions: [],
      // 临时ID计数器，用于前端临时识别问题
      tempIdCounter: 1
    };
  },
  created() {
    this.surveyId = this.$route.params.id;
    if (this.surveyId) {
      this.getSurveyData();
    }
    // 模拟部门、角色和用户数据
    this.deptOptions = [
      { deptId: '1', deptName: '总经办' },
      { deptId: '2', deptName: '人力资源部' },
      { deptId: '3', deptName: '技术部' },
      { deptId: '4', deptName: '市场部' },
      { deptId: '5', deptName: '财务部' }
    ];
    this.roleOptions = [
      { roleId: '1', roleName: '管理员' },
      { roleId: '2', roleName: '普通员工' },
      { roleId: '3', roleName: '部门经理' },
      { roleId: '4', roleName: '总监' }
    ];
    this.userOptions = [
      { userId: '1', userName: '张三' },
      { userId: '2', userName: '李四' },
      { userId: '3', userName: '王五' },
      { userId: '4', userName: '赵六' }
    ];
  },
  methods: {
    /** 获取问卷数据 */
    getSurveyData() {
      this.loading = true;
      getSurveyQuestionnaire(this.surveyId).then(response => {
        this.surveyInfo = response.data;
        
        // 为现有问题添加临时ID
        if (this.surveyInfo.questions) {
          this.surveyInfo.questions.forEach(question => {
            question.tempId = this.tempIdCounter++;
          });
        } else {
          this.surveyInfo.questions = [];
        }
        
        this.loading = false;
      });
    },
    /** 返回问卷列表 */
    goBack() {
      this.$router.push('/system/survey/index');
    },
    /** 显示添加问题对话框 */
    showAddQuestionDialog() {
      this.addQuestionDialogVisible = true;
    },
    /** 显示目标设置对话框 */
    showTargetSettingDialog() {
      this.targetSettingDialogVisible = true;
    },
    /** 保存目标设置 */
    saveTargetSetting() {
      this.targetSettingDialogVisible = false;
      this.$message.success('目标设置保存成功');
    },
    /** 预览问卷 */
    previewSurvey() {
      this.previewDialogVisible = true;
    },
    /** 添加问题 */
    addQuestion(type) {
      const newQuestion = {
        tempId: this.tempIdCounter++,
        type: type,
        title: '',
        required: 1,
        sort: this.surveyInfo.questions.length + 1
      };
      
      // 根据类型设置默认值
      if (type === 'radio' || type === 'checkbox') {
        newQuestion.options = JSON.stringify([
          { label: '选项1' },
          { label: '选项2' },
          { label: '选项3' }
        ]);
      } else if (type === 'rate') {
        newQuestion.maxScore = 5;
      } else if (type === 'text') {
        newQuestion.rows = 3;
        newQuestion.placeholder = '请输入...';
      }
      
      this.surveyInfo.questions.push(newQuestion);
      this.addQuestionDialogVisible = false;
    },
    /** 删除问题 */
    deleteQuestion(index) {
      this.$confirm('确认删除该问题吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.surveyInfo.questions.splice(index, 1);
        this.$message.success('删除成功');
      }).catch(() => {});
    },
    /** 复制问题 */
    copyQuestion(index) {
      const question = this.surveyInfo.questions[index];
      const copy = JSON.parse(JSON.stringify(question));
      copy.tempId = this.tempIdCounter++;
      copy.title = copy.title + ' (复制)';
      copy.sort = this.surveyInfo.questions.length + 1;
      this.surveyInfo.questions.push(copy);
      this.$message.success('复制成功');
    },
    /** 移动问题 */
    moveQuestion(index, direction) {
      if (direction === 'up' && index > 0) {
        const temp = this.surveyInfo.questions[index];
        this.$set(this.surveyInfo.questions, index, this.surveyInfo.questions[index - 1]);
        this.$set(this.surveyInfo.questions, index - 1, temp);
      } else if (direction === 'down' && index < this.surveyInfo.questions.length - 1) {
        const temp = this.surveyInfo.questions[index];
        this.$set(this.surveyInfo.questions, index, this.surveyInfo.questions[index + 1]);
        this.$set(this.surveyInfo.questions, index + 1, temp);
      }
      this.updateQuestionSort();
    },
    /** 更新问题排序 */
    updateQuestionSort() {
      this.surveyInfo.questions.forEach((question, index) => {
        question.sort = index + 1;
      });
    },
    /** 解析选项 */
    parseOptions(options) {
      try {
        return options ? JSON.parse(options) : [];
      } catch (e) {
        return [];
      }
    },
    /** 添加选项 */
    addOption(question) {
      const options = this.parseOptions(question.options);
      options.push({ label: '新选项' });
      question.options = JSON.stringify(options);
    },
    /** 删除选项 */
    deleteOption(question, index) {
      const options = this.parseOptions(question.options);
      options.splice(index, 1);
      question.options = JSON.stringify(options);
    },
    /** 更新问题选项 */
    updateQuestionOptions(question, options) {
      question.options = JSON.stringify(options);
    },
    /** 保存问卷 */
    saveSurvey() {
      if (!this.surveyInfo.title) {
        this.$message.error('请输入问卷标题');
        return;
      }
      
      if (!this.surveyInfo.startTime) {
        this.$message.error('请选择开始时间');
        return;
      }
      
      if (!this.surveyInfo.endTime) {
        this.$message.error('请选择结束时间');
        return;
      }
      
      // 验证问题
      for (let i = 0; i < this.surveyInfo.questions.length; i++) {
        const question = this.surveyInfo.questions[i];
        if (!question.title) {
          this.$message.error(`第${i + 1}个问题标题不能为空`);
          return;
        }
        
        if ((question.type === 'radio' || question.type === 'checkbox') && this.parseOptions(question.options).length === 0) {
          this.$message.error(`第${i + 1}个问题必须至少有一个选项`);
          return;
        }
      }
      
      this.saveLoading = true;
      
      const data = JSON.parse(JSON.stringify(this.surveyInfo));
      
      // 移除临时ID
      if (data.questions) {
        data.questions.forEach(question => {
          delete question.tempId;
        });
      }
      
      if (this.surveyId) {
        // 更新问卷
        updateSurveyQuestionnaire(data).then(response => {
          this.$message.success('保存成功');
          this.saveLoading = false;
          this.goBack();
        }).catch(() => {
          this.saveLoading = false;
        });
      } else {
        // 新增问卷
        addSurveyQuestionnaire(data).then(response => {
          this.$message.success('创建成功');
          this.saveLoading = false;
          this.goBack();
        }).catch(() => {
          this.saveLoading = false;
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.survey-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .survey-title {
    font-size: 18px;
    font-weight: bold;
    
    .placeholder {
      color: #999;
    }
  }
  
  .survey-actions {
    display: flex;
    gap: 10px;
  }
}

.survey-basic-info {
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 15px;
  
  .form-label {
    margin-bottom: 5px;
    font-weight: bold;
    
    &.required:after {
      content: '*';
      color: #f56c6c;
      margin-left: 5px;
    }
  }
}

.form-row {
  display: flex;
  margin-bottom: 15px;
}

.survey-questions {
  .question-item {
    margin-bottom: 15px;
  }
  
  .question-card {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 15px;
    background-color: #fff;
    
    &:hover {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    
    .question-header {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      
      .drag-handle {
        cursor: move;
        margin-right: 10px;
        color: #999;
      }
      
      .question-index {
        font-weight: bold;
        margin-right: 10px;
      }
      
      .question-type-tag {
        padding: 2px 8px;
        background-color: #ecf5ff;
        color: #409eff;
        border-radius: 10px;
        font-size: 12px;
      }
      
      .question-actions {
        margin-left: auto;
        display: flex;
        gap: 5px;
      }
    }
  }
}

.add-question-container {
  margin: 20px 0;
  text-align: center;
  
  .add-question-btn {
    width: 60%;
    border: 1px dashed #d9d9d9;
    color: #606266;
    
    &:hover {
      border-color: #409eff;
      color: #409eff;
    }
  }
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  
  .el-input {
    margin-right: 10px;
  }
}

.add-option {
  margin-top: 10px;
}

.question-type-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  
  .question-type-item {
    border: 1px solid #ebeef5;
    padding: 15px;
    border-radius: 4px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      border-color: #409eff;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    
    .question-type-icon {
      font-size: 24px;
      margin-bottom: 10px;
      color: #409eff;
    }
    
    .question-type-name {
      font-size: 14px;
    }
  }
}

.survey-setting {
  .setting-content {
    .setting-item {
      margin-bottom: 15px;
      
      .setting-label {
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .setting-value {
        color: #606266;
      }
    }
  }
}

// 预览样式
.preview-container {
  padding: 20px;
}
.preview-title {
  text-align: center;
  margin-bottom: 15px;
}
.preview-description {
  margin-bottom: 20px;
  color: #666;
  text-align: center;
}
.preview-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  color: #999;
  font-size: 14px;
}
.question-list {
  margin-top: 30px;
}
.question-item {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}
.question-title {
  font-weight: bold;
  margin-bottom: 10px;
}
.question-content {
  margin-left: 20px;
}
.required {
  color: #f56c6c;
  margin-left: 5px;
}
.empty-questions {
  text-align: center;
  color: #999;
  padding: 30px;
}

// 拖拽相关样式
.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}
</style> 